import amqp from 'amqplib';

let connection;
let channel;

export async function connectRabbitMQ() {
  try {
    connection = await amqp.connect(process.env.RABBITMQ_URL);
    channel = await connection.createChannel();
    await channel.assertQueue('image_processing');
    console.log('Connected to RabbitMQ');
  } catch (error) {
    console.error('RabbitMQ connection error:', error);
  }
}

export async function addToQueue(queueName, data) {
  if (!channel) {
    await connectRabbitMQ();
  }
  await channel.sendToQueue(queueName, Buffer.from(JSON.stringify(data)));
}

export async function consumeFromQueue(queueName, callback) {
  if (!channel) {
    await connectRabbitMQ();
  }
  await channel.consume(queueName, (msg) => {
    if (msg !== null) {
      const data = JSON.parse(msg.content.toString());
      callback(data);
      channel.ack(msg);
    }
  });
}